package com.slipper.system.scheduled;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import com.slipper.system.api.schedule.bo.ScheduleBO;
import com.slipper.system.api.schedule.service.IScheduleSv;

public class ScheduledListener implements ApplicationRunner {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private IScheduleSv scheduleSv;

    @Override
    public void run(ApplicationArguments args) {
        this.init();
    }
    
    /**
     * 项目启动时，初始化定时器
     */
    public void init() {
        ScheduleBO bo = new ScheduleBO();
        List<ScheduleBO> scheduleList = null;
        boolean success = false;
        while (!success) {
            try {
                scheduleList = this.scheduleSv.queryList(bo).getData();
                success = true;
            } catch (Exception e) {
                try {
                    Thread.sleep(5 * 1000);
                } catch (InterruptedException ignored) {
                }
            }
        }

        logger.info("初始化调度数量：{}", scheduleList.size());
        for (ScheduleBO scheduleBO : scheduleList) {
            try {
                logger.info("初始化调度：{}", scheduleBO);
                ScheduledUtil.createScheduleJob(scheduleBO);
            } catch (Exception e) {
                logger.error("创建定时任务调度失败！", e);
            }
        }
    }
}
